import time
import threading

class RateLimiter:
    """令牌桶限流器"""
    def __init__(self, max_calls: int, period: float):
        self.max_calls = max_calls
        self.period = period
        self._tokens = max_calls
        self._last_refill = time.time()
        self._lock = threading.Lock()

    def acquire(self):
        with self._lock:
            self._refill()
            if self._tokens <= 0:
                time.sleep(self._get_wait_time())
                self._refill()
            self._tokens -= 1

    def _refill(self):
        now = time.time()
        elapsed = now - self._last_refill
        if elapsed > self.period:
            self._tokens = self.max_calls
            self._last_refill = now

    def _get_wait_time(self):
        return self.period - (time.time() - self._last_refill) 